let log4js = require('log4js');
let log_config = require('../config/log_config');

//加载配置文件
log4js.configure(log_config);

let logUtil = {};

let errorLogger = log4js.getLogger('errorLogger');

let resLogger = log4js.getLogger('resLogger');

//封装错误日志
logUtil.logError = (ctx,error,resTime) => {

	if(ctx&&error){

		errorLogger.error(formatError(ctx,error,resTime));

	}
}

//封装响应日志
logUtil.logResponse = (ctx,resTime) => {

	if(ctx){

		resLogger.info(formatRes(ctx,resTime))
	}
}

//格式化请求日志
let formatReq = (req,resTime) => {

	let logTest = "";
	//获取请求方法
	let method = req.method;

	logTest += "request method:"+method + "\n";
	//请求原始地址
	logTest += "request originalUrl:"+req.originalUrl + "\n";
	//客户端ip
	logTest += "client ip:"+req.ip + "\n";

	//请求参数
	if(method === 'GET'){

		logTest += "request query:"+JSON.stringify(req.query) + "\n";

	}else{

		logTest += "request body:"+JSON.stringify(req.body) + "\n";
	}

	//服务器响应时间
	logTest += "response time:"+ resTime;

	return logTest;

}

//格式化错误日志

let formatError = (ctx,error,resTime) => {

	let logTest = "";
		//错误日志开始
		logTest+= "\n"+"********error log start********"+"\n";
		//添加请求日志
		logTest+= formatReq(ctx.request,resTime) + "\n";
		//错误名称
		logTest+="err name:"+error.name + "\n";
		//错误信息
		logTest+="err message:"+error.message + "\n";
		//错误详情
		logTest+="err stack:"+error.stack + "\n";

		logTest+= "********error log end********"+"\n";


		return logTest;

}

//格式化响应日志
let formatRes= (ctx,resTime) => {

	let logTest = "";

	//响应日志开始
	logTest+= "\n"+"********response log start********"+"\n";
	//添加请求日志
	logTest+= formatReq(ctx.request,resTime) + "\n";
	//响应状态码
	logTest+= "res status:"+ctx.status+"\n";
	//响应内容
	logTest+= "res body:"+JSON.stringify(ctx.body)+"\n";
	//响应内容结束
	logTest+="********response log end********"+"\n";

	return logTest;

}

module.exports = logUtil;
